package ca.abubakrsagar.breadboardsim;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 * @author Sagar Desai, Mohammad Abubakr Last Modified: May 29,2012 This class
 *         handles the menubar and its various options. It extends JMenuBar
 */
public class MenuBar extends JMenuBar {

	// Menus on the menu bar.
	private JMenu file = new JMenu("File");
	private JMenu help = new JMenu("Help");

	// Items on the menu bar.
	private JMenuItem open = new JMenuItem("Open..");
	private JMenuItem save = new JMenuItem("Save..");
	private JMenuItem exit = new JMenuItem("Exit..");
	private JMenuItem about = new JMenuItem("About..");

	// The menu bar controller.
	private MenuBarController controller = new MenuBarController(this);

	private BreadboardPanel breadboardPanel; // The breadboard panel.

	private JFileChooser fc = new JFileChooser(); // The JFile chooser used to
													// allow the user to select
													// files.

	/**
	 * Creates a new menu bar. Associates the breadboard panel and adds all
	 * required items and listeners.
	 */
	public MenuBar(BreadboardPanel breadboardPanel) {
		this.breadboardPanel = breadboardPanel;

		// Add required items and menus.
		this.add((file));
		this.add((help));
		file.add(open);
		file.add(save);
		file.add(exit);
		help.add(about);

		// Add required action listeners.
		open.addActionListener(controller);
		save.addActionListener(controller);
		exit.addActionListener(controller);
		about.addActionListener(controller);

	}

	/**
	 * @return The open menu item.
	 */
	public JMenuItem getOpen() {
		return open;
	}

	/**
	 * @return The save menu item.
	 */
	public JMenuItem getSave() {
		return save;
	}

	/**
	 * @return The exit menu item.
	 */
	public JMenuItem getExit() {
		return exit;
	}

	/**
	 * @return The about menu item.
	 */
	public JMenuItem getAbout() {
		return about;
	}

	/**
	 * Opens an about window to be displayed for the user.
	 */
	public void openAbout() {

		// Setup a new window to display help information to the user.
		JFrame aboutFrame = new JFrame("About us");
		aboutFrame.setSize(650, 500);

		JPanel aboutPanel = new JPanel();
		aboutFrame.setContentPane(aboutPanel);
		JTextArea aboutLabel = new JTextArea(
				"Welcome! Breadboard Simulator is a program that can be used to test circuits on a virtual breadboard with ease. "
						+ "\nYou can add  components to the breadboard by double clicking the components on the left side. This will "
						+ "\n add them to the tool box under your breadboard.You can now drag them from the tool box to the breadboard "
						+ "\n to place them. To create wire, right click the starting spot and then right click the ending spot and a wire will "
						+ "\n appear between the two points. To turn the circuit on, simply click on the main switch.\n \n Author: Sagar Desai, Mohammad Abubakr");
		aboutLabel.setBackground(null);
		aboutPanel.add(aboutLabel);
		aboutFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		aboutFrame.setLocation(
				(int) (dim.getWidth() - aboutFrame.getWidth()) / 2,
				(int) (dim.getHeight() - aboutFrame.getHeight()) / 2);

		aboutFrame.setVisible(true);
	}

	/**
	 * Allows the user to load a previous project through a text file.
	 */
	public void openFileChooser() throws FileNotFoundException {

		fc.showOpenDialog(this);
		File file = fc.getSelectedFile();
		Scanner in = new Scanner(file);

		// Loop through the text file locating the locations of the components
		// and mapping them onto the component map.
		for (int i = 0; i < 14; i++) {			
			for (int j = 0; j < 64; j++) {
				String component = in.next();
				System.out.println(component);
				if (component.equalsIgnoreCase("L")) {
					String red = in.next();
					String green = in.next();
					String blue = in.next();
					LED led = new LED(new Color(Integer.parseInt(red),
							Integer.parseInt(green), Integer.parseInt(blue)));
					breadboardPanel.getBreadboard().setComponent(i, j, led);
				} else if (component.equalsIgnoreCase("W")) {

					// Wire wire = new Wire(j+1,i+1,);
					// breadboardPanel.getBreadboard().setComponent(i, j, wire);

				} else if (component.equalsIgnoreCase("S")) {
					String property = in.next();

					if (property.equalsIgnoreCase("O")) {
						Switch switchc = new Switch(true);
						breadboardPanel.getBreadboard().setComponent(i, j,
								switchc);
					} else {
						Switch switchc = new Switch(false);
						breadboardPanel.getBreadboard().setComponent(i, j,
								switchc);
					}

				} else if (component.equalsIgnoreCase("R")) {

					String property = in.next();

					if (property.equalsIgnoreCase("H")) {
						String ohms = in.next();
						Resistor resistor = new Resistor(
								Integer.parseInt(ohms), 0);
						breadboardPanel.getBreadboard().setComponent(i, j,
								resistor);
					} else {
						String ohms = in.next();
						Resistor resistor = new Resistor(
								Integer.parseInt(ohms), 1);
						breadboardPanel.getBreadboard().setComponent(i, j,
								resistor);
					}

					Resistor resistor = new Resistor(j, j);
					breadboardPanel.getBreadboard()
							.setComponent(i, j, resistor);
				}
			}
			
		}

		breadboardPanel.update();

	}

	/**
	 * Saves the user's breadboard layout to a text file.
	 */
	public void saveFile() throws IOException {
		String name = JOptionPane.showInputDialog(null,			
				"Enter file name (include the extension): ", "File Chooser", 1);	//displays an input dialouge 
																					//that asks for the name of the file	
		PrintWriter out = null;					
		File file = new File(name + ".txt");			//makes a new file object
		file.createNewFile();							//makes the actual file
		out = new PrintWriter(file);					
		for (int i = 0; i < 14; i++) { // loops through whole array
			for (int j = 0; j < 64; j++) {

				// if spot isn't empty
				if (breadboardPanel.getBreadboard().getComponent(i, j) != null) {
					boolean found = false;		
					//loops through each array list to find the component at the current spot in the array
					if (!found){					//if component has not been found yet					
						for (int k = 0; k < breadboardPanel.getBreadboard()		
								.getLED().size(); k++) { // loops through LEDs
							if (breadboardPanel.getBreadboard().getLED().get(k) == breadboardPanel   //if component in array list
									.getBreadboard().getComponent(i, j)) {							// is same as the one in the array
								out.print("L ");								// prints out L to file
								int red = breadboardPanel.getBreadboard()		//gets the RGB values
										.getLED().get(k).getLedColor().getRed();
								int green = breadboardPanel.getBreadboard()
										.getLED().get(k).getLedColor()
										.getGreen();
								int blue = breadboardPanel.getBreadboard()		
										.getLED().get(k).getLedColor()
										.getBlue();
								out.print(red + " " + green + " " + blue);		// prints out the RGB values to the file	
								out.println();
								found = true;									// component has been found
								break;
							}
						}
					}
					if (!found) {		//if component has not been found yet
						for (int l = 0; l < breadboardPanel.getBreadboard()		// loops throught resistors
								.getResistor().size(); l++) {					
							if (breadboardPanel.getBreadboard().getResistor()	//finds resistor in arraylist
									.get(l) == breadboardPanel.getBreadboard()
									.getComponent(i, j)) {
								out.print("R ");								//prints out R
								int ohms = breadboardPanel.getBreadboard()		// gets the resistor's ohms value
										.getResistor().get(l).getOhms();
								out.print(ohms);								//prints out the ohms value
								out.println();					// moves cursor to next line
								found = true;					// component has been found
								break;
							}
						}
					}

					
					if (!found) {			//if component has not been found yet
						for (int l = 0; l < breadboardPanel.getBreadboard()
								.getSwitch().size(); l++) {						//loops through switches
							if (breadboardPanel.getBreadboard().getSwitch()		// finds switch
									.get(l) == breadboardPanel.getBreadboard()
									.getComponent(i, j)) {
								out.print("S ");								// writes S to file
								if (breadboardPanel.getBreadboard().getSwitch()		// determines whether the switch is on or off
										.get(l).isOn()) {
									out.print("O");									// if its on, prints O, else prints F
								} else {
									out.print("F");
								}
								out.println();				// moves cursor to next line
								found = true;				// component has been found
								break;
							}
						}
					}

					if (!found) {		//if component has not been found yet
						out.print("W");		//prints out W
						out.println();		// moves cursor to next line
					}

				} else {			// if component still has not been found, then it is empty
					out.print("N");
					out.println();	// moves cursor to next line
				}
			}
		}
		out.close();		//closes file
	}

}
